// API基础URL
const API_BASE_URL = '';

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentSections = document.querySelectorAll('.content-section');

    // 初始化：显示供应商管理页面
    showSection('supplier');
    loadSuppliers();

    // 导航链接事件监听
    navLinks.forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();
            const target = this.getAttribute('data-target');
            showSection(target);
            
            // 根据选中的菜单加载对应数据
            switch(target) {
                case 'supplier':
                    loadSuppliers();
                    break;
                case 'product':
                    loadProducts();
                    break;
                case 'order':
                    loadOrders();
                    break;
                case 'order-item':
                    loadOrderItems();
                    break;
            }
        });
    });

    // 刷新按钮事件监听
    document.getElementById('refresh-supplier-btn').addEventListener('click', loadSuppliers);
    document.getElementById('refresh-product-btn').addEventListener('click', loadProducts);
    document.getElementById('refresh-order-btn').addEventListener('click', loadOrders);
    document.getElementById('refresh-order-item-btn').addEventListener('click', loadOrderItems);

    // 创建按钮事件监听
    document.getElementById('create-supplier-btn').addEventListener('click', function() {
        alert('创建供应商功能待实现');
    });
    
    document.getElementById('create-product-btn').addEventListener('click', function() {
        alert('创建商品功能待实现');
    });
    
    document.getElementById('create-order-btn').addEventListener('click', function() {
        alert('创建订单功能待实现');
    });
});

// 显示指定部分，隐藏其他部分
function showSection(sectionId) {
    const navLinks = document.querySelectorAll('.nav-link');
    const contentSections = document.querySelectorAll('.content-section');

    // 移除所有激活状态
    navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('data-target') === sectionId) {
            link.classList.add('active');
        }
    });

    // 隐藏所有内容区域
    contentSections.forEach(section => {
        section.classList.add('hidden');
    });

    // 显示目标区域
    const targetSection = document.getElementById(sectionId + '-section');
    if (targetSection) {
        targetSection.classList.remove('hidden');
    }
}

// 加载供应商数据
function loadSuppliers() {
    // 这里应该调用后端API获取数据
    // 暂时使用模拟数据
    const suppliers = [
        {id: 1, supplierCode: 'SUP001', supplierName: '华为技术有限公司', contactPerson: '张经理', contactPhone: '0755-12345678', address: '深圳市龙岗区华为总部', status: 'ACTIVE', createdTime: '2023-01-15 09:30:00'},
        {id: 2, supplierCode: 'SUP002', supplierName: '小米科技有限公司', contactPerson: '李经理', contactPhone: '010-87654321', address: '北京市海淀区小米科技园', status: 'ACTIVE', createdTime: '2023-02-20 14:15:00'},
        {id: 3, supplierCode: 'SUP003', supplierName: '苹果电脑贸易有限公司', contactPerson: '王经理', contactPhone: '021-12345678', address: '上海市浦东新区苹果大厦', status: 'INACTIVE', createdTime: '2023-03-10 11:45:00'}
    ];
    
    renderSuppliersTable(suppliers);
}

// 渲染供应商表格
function renderSuppliersTable(suppliers) {
    const tbody = document.querySelector('#suppliers-table tbody');
    tbody.innerHTML = '';
    
    if (!suppliers || suppliers.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" style="text-align: center;">暂无供应商数据</td></tr>';
        return;
    }
    
    suppliers.forEach(supplier => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${supplier.id}</td>
            <td>${supplier.supplierCode}</td>
            <td>${supplier.supplierName}</td>
            <td>${supplier.contactPerson}</td>
            <td>${supplier.contactPhone}</td>
            <td>${supplier.address}</td>
            <td><span class="status-badge status-${supplier.status}">${getStatusText(supplier.status)}</span></td>
            <td>${supplier.createdTime}</td>
            <td>
                <button class="btn btn-primary btn-sm">编辑</button>
                <button class="btn btn-danger btn-sm">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 加载商品数据
function loadProducts() {
    // 这里应该调用后端API获取数据
    // 暂时使用模拟数据
    const products = [
        {id: 1, productCode: 'PROD001', productName: '智能手机A100', categoryId: 1, unit: '台', costPrice: 1500.00, salePrice: 2999.00, stockQuantity: 100, status: 'ACTIVE', createdTime: '2023-01-15 09:30:00'},
        {id: 2, productCode: 'PROD002', productName: '笔记本电脑B200', categoryId: 2, unit: '台', costPrice: 3500.00, salePrice: 5999.00, stockQuantity: 50, status: 'ACTIVE', createdTime: '2023-02-20 14:15:00'},
        {id: 3, productCode: 'PROD003', productName: '平板电脑C300', categoryId: 1, unit: '台', costPrice: 1200.00, salePrice: 2499.00, stockQuantity: 80, status: 'INACTIVE', createdTime: '2023-03-10 11:45:00'}
    ];
    
    renderProductsTable(products);
}

// 渲染商品表格
function renderProductsTable(products) {
    const tbody = document.querySelector('#products-table tbody');
    tbody.innerHTML = '';
    
    if (!products || products.length === 0) {
        tbody.innerHTML = '<tr><td colspan="11" style="text-align: center;">暂无商品数据</td></tr>';
        return;
    }
    
    products.forEach(product => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${product.id}</td>
            <td>${product.productCode}</td>
            <td>${product.productName}</td>
            <td>${product.categoryId}</td>
            <td>${product.unit}</td>
            <td>¥${product.costPrice.toFixed(2)}</td>
            <td>¥${product.salePrice.toFixed(2)}</td>
            <td>${product.stockQuantity}</td>
            <td><span class="status-badge status-${product.status}">${getStatusText(product.status)}</span></td>
            <td>${product.createdTime}</td>
            <td>
                <button class="btn btn-primary btn-sm">编辑</button>
                <button class="btn btn-danger btn-sm">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 加载订单数据
function loadOrders() {
    // 这里应该调用后端API获取数据
    // 暂时使用模拟数据
    const orders = [
        {id: 1, orderNumber: 'PO202301001', supplierID: 1, totalAmount: 29990.00, orderDate: '2023-04-01', status: 'APPROVED', creationTime: '2023-04-01 10:30:00'},
        {id: 2, orderNumber: 'PO202301002', supplierID: 2, totalAmount: 119980.00, orderDate: '2023-04-05', status: 'SUBMITTED', creationTime: '2023-04-05 14:20:00'},
        {id: 3, orderNumber: 'PO202301003', supplierID: 3, totalAmount: 49980.00, orderDate: '2023-04-10', status: 'DRAFT', creationTime: '2023-04-10 09:15:00'}
    ];
    
    renderOrdersTable(orders);
}

// 渲染订单表格
function renderOrdersTable(orders) {
    const tbody = document.querySelector('#orders-table tbody');
    tbody.innerHTML = '';
    
    if (!orders || orders.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无订单数据</td></tr>';
        return;
    }
    
    orders.forEach(order => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${order.id}</td>
            <td>${order.orderNumber}</td>
            <td>${order.supplierID}</td>
            <td>¥${order.totalAmount.toFixed(2)}</td>
            <td>${order.orderDate}</td>
            <td><span class="status-badge status-${order.status}">${getStatusText(order.status)}</span></td>
            <td>${order.creationTime}</td>
            <td>
                <button class="btn btn-primary btn-sm">查看</button>
                <button class="btn btn-warning btn-sm">编辑</button>
                <button class="btn btn-danger btn-sm">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 加载订单明细数据
function loadOrderItems() {
    // 这里应该调用后端API获取数据
    // 暂时使用模拟数据
    const orderItems = [
        {id: 1, orderID: 1, productID: 1, quantity: 10, unitPrice: 2999.00, subtotal: 29990.00, createdTime: '2023-04-01 10:30:00'},
        {id: 2, orderID: 2, productID: 2, quantity: 20, unitPrice: 5999.00, subtotal: 119980.00, createdTime: '2023-04-05 14:20:00'},
        {id: 3, orderID: 3, productID: 3, quantity: 20, unitPrice: 2499.00, subtotal: 49980.00, createdTime: '2023-04-10 09:15:00'}
    ];
    
    renderOrderItemsTable(orderItems);
}

// 渲染订单明细表格
function renderOrderItemsTable(orderItems) {
    const tbody = document.querySelector('#order-items-table tbody');
    tbody.innerHTML = '';
    
    if (!orderItems || orderItems.length === 0) {
        tbody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无订单明细数据</td></tr>';
        return;
    }
    
    orderItems.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.id}</td>
            <td>${item.orderID}</td>
            <td>${item.productID}</td>
            <td>${item.quantity}</td>
            <td>¥${item.unitPrice.toFixed(2)}</td>
            <td>¥${item.subtotal.toFixed(2)}</td>
            <td>${item.createdTime}</td>
            <td>
                <button class="btn btn-primary btn-sm">查看</button>
                <button class="btn btn-danger btn-sm">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 获取状态显示文本
function getStatusText(status) {
    const statusMap = {
        'ACTIVE': '启用',
        'INACTIVE': '禁用',
        'DRAFT': '草稿',
        'SUBMITTED': '已提交',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝',
        'CLOSED': '已关闭'
    };
    return statusMap[status] || status;
}